﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Grids;
using VAdvantage.Apps;
using VAdvantage.Controls;
using VAdvantage.Classes;
using System.Collections;
using System.Text;
using System.ComponentModel;
using VAdvantage.Model;
using VAdvantage.Utility;
using System.Data;
using VAdvantage.DataBase;
using System.Windows.Data;
using SL4PopupMenu;
using System.Threading;
using VAdvantage.Logging;

namespace VAdvantage.Panels
{
    public partial class GridController : UserControl, IDisposable
    {
        /** Model Tab                   */

        private GridTab mTab = null;
        /** window Number                      */
        private int windowNo;
        /** Only Multi-Row exist        */
        private bool onlyMultiRow = false;
        /** Single/Multi Row indicator  */
        private bool singleRow = true;
        /** Veto Active                 */
        private bool vetoActive = false;
        /** Tree Panel (optional)       */
        //private VTreePanel vTreePanel = null;

        private DataStatusEvent _datastatusEvent = null;
        private APanel aPanel = null;

        //Image List for VtreeView O

        //flag setting position of datasource
        public bool isPostionSetting = false;
        private bool findSelectedNode = true;

        private bool _showMiniGrid = false;

        private bool _showClient = false;
        private bool _showOrg = false;

        private DataUtil.DataObject currentRow = null;

        //private IList bindingSource = null;

        private BindingSource bindingSource = null;

        private int _currentPage = 0;


        private bool _doPaging = false;

        public event EventHandler OnNewRowInserted;

        public event EventHandler OnManualRowInserting;

        /* add action pane link */
        public List<Object> leftPaneLinkItems = new List<Object>();
        public List<Object> rightPaneLinkItems = new List<Object>();
        public FrameworkElement TreePaneLeftLinks
        {
            get;
            set;
        }
        public FrameworkElement TreePaneRightLinks
        {
            get;
            set;
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public GridController()
        {
            InitializeComponent();
            vTable.CellEditEnded += new EventHandler<DataGridCellEditEndedEventArgs>(vTable_CellEditEnded);
            vTable.DelyedCellEditEnd += new EventHandler(vTable_DelyedCellEditEnd);
        }



        /// <summary>
        /// COnstructor
        /// </summary>
        /// <param name="rowHeader">show row header or not to gridview</param>
        public GridController(bool rowHeader)
            : this(rowHeader, false)
        {
        }

        /// <summary>
        /// COnstructor
        /// </summary>
        /// <param name="rowHeader">show row header or not to gridview</param>
        public GridController(bool rowHeader, bool doPaging)
            : this()
        {
            //_showClientOrg = Utility.Envs.GetCtx().GetShowClientOrg();

            int level = Utility.Envs.GetCtx().GetShowClientOrg();

            if (level == Envs.SHOW_CLIENT_ONLY)
            {
                _showClient = true;

            }
            else if (level == Envs.SHOW_ORG_ONLY)
            {
                _showOrg = true;
            }
            else if (level == Envs.SHOW_CLIENT_ORG)
            {
                _showOrg = true;
                _showClient = true;
            }

            _showMiniGrid = Utility.Envs.GetCtx().GetShowMiniGrid();
            JbInit();
            vTable.ShowRowNumber = rowHeader;
            //vTable.CanUserSortColumns = false;
            _doPaging = doPaging;

            //CommonFunctions.SetDataGridPrperties(vTable);

        }
        void vTable_CellEditEnded(object sender, DataGridCellEditEndedEventArgs e)
        {
            GridField field = ((IDataGridColumn)e.Column).Field;
            PerformGridCallouts(field, vTable.IsCellValuechanged);
            vTable.IsCellValuechanged = false;
        }

        public void PerformGridCallouts(GridField field, bool isPerform)
        {
            if (mTab.CurrentRowDataObject != null && isPerform)
            {
                vTable.IsEnabled = false;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    mTab.CurrentRowDataObject.BeginEdit();
                    mTab.ProcessDependentAndCallOut(field);
                    mTab.CurrentRowDataObject.EndEdit();

                    this.Dispatcher.BeginInvoke(() => vTable.IsEnabled = true);
                }
                );
            }
        }

        void vTable_DelyedCellEditEnd(object sender, EventArgs e)
        {
            if (sender is IControl)
            {
                PerformGridCallouts(((IControl)sender).GetField(), !vTable.isCellinEditMode);
            }
            vTable.isCellinEditMode = false;
        }

        private void JbInit()
        {
            //this.spltControlsPane.Panel1.Controls.Add(vPanel);
            // this.spltControlsPane.Panel2.Controls.Add(vTable);
            // this.pnlTop.BackColor = DataBase.GlobalVariable.TAB_HEADER_PANEL_BACKCOLOR;
            // this.lblTabName.ForeColor = DataBase.GlobalVariable.TAB_HEADER_LABEL_FORECOLOR;
        }

        /// <summary>
        ///
        /*  - Map table to model
         - Update (multi-row) table info with renderers/editors
         - build single-row panel
         - initialize display
        */
        /// </summary>
        /// <param name="form"></param>
        /// <param name="mTab"></param>
        /// <param name="windowNo"></param>
        /// <param name="onlyMultiRow"></param>
        /// <returns></returns>

        Logging.VLogger log = Logging.VLogger.GetVLogger(typeof(GridController).FullName);
        TreeSearchPanel tree = null;
        public bool InitGrid(Grids.GridTab tab, bool onlyMultirow, int windowNum, APanel pnl, GridWindow mWindow)
        {
            log.Config("(" + tab.ToString() + ")");
            mTab = tab;
            windowNo = windowNum;
            onlyMultiRow = onlyMultirow;
            aPanel = pnl;
            //BindDefault TableModel o binding Source
            //    this.BindingSource.DataSource = tab.GetDefaultTableModel();

            // this.Name = "GC-" + mTab.GetName();
            //Role Check
            Model.MRole role = Model.MRole.GetDefault();
            tab.GetTableObj().CreateBindableObject();
            tab.GetTableObj().DoPaging = _doPaging;

            //bindingSource =  tab.GetDataTable();
            bindingSource = null;

            if (!role.IsDisplayClient() || !_showClient)
                tab.GetField("AD_Client_ID").SetDisplayed(false);
            if (!role.IsDisplayOrg() || !_showOrg)
                tab.GetField("AD_Org_ID").SetDisplayed(false);

            //Set Up MultiRowTable

            //  Update Table Info -------------------------------------------------


            int size = vTable.SetupGridTable(aPanel, mTab);

            //  Single Row  -------------------------------------------------------
            if (!onlyMultiRow)
            {
                //	Set Softcoded Mnemonic &x
                //for (int i = 0; i < size; i++)
                //{
                //    GridField mField = mTab.GetField(i);
                //    if (mField.IsDisplayed())
                //        //vPanel.setMnemonic(mField);
                //}   //  for all fields

                //	Add Fields
                for (int i = 0; i < size; i++)
                {
                    GridField mField = mTab.GetField(i);
                    if (mField.IsDisplayed())
                    {
                        IControl vControl = VControlFactory.GetControl(mTab, mField, false, false, false);
                        //if (vControl == null)
                        //{
                        //    log.Warning("Editor not created for " + mField.GetColumnName());
                        //    continue;
                        //}
                        if (vControl is IControl && vControl.GetName() != null)
                        {
                            vControl.BindValue = vControl.GetName().ToUpper();
                        }


                        //if (vControl is Grids.VComboBox)
                        //{
                        //    cmbControls.Add((Grids.VComboBox)vControl);
                        //}
                        //  MField => VEditor - New Field value to be updated to editor
                        //mField.addPropertyChangeListener(vEditor);
                        //  VEditor => this - New Editor value to be updated here (MTable)
                        //vEditor.addVetoableChangeListener(this);
                        //  Add to VPanel
                        //mField.SetControl = vControl;
                        vControl.SetReadOnly(true);
                        vPanel.AddField(vControl, mField);
                        ////  APanel Listen to buttons

                        vControl.VetoableChangeListener += new EventHandler(aPanel.ValueChanged);

                        if (vControl is ITextChangedEvent)
                        {
                            ((ITextChangedEvent)vControl).FireTextChanged += new EventHandler(aPanel.FireTextChanged);
                        }
                        if (mField.GetDisplayType() == DisplayType.Button && aPanel != null)
                        {
                            if (!mField.GetIsLink())
                            {
                                ((Button)vControl).Click += new RoutedEventHandler(aPanel.btn_click); //new EventHandler(aPanel.btn_click);
                            }
                            else
                            {
                                ((VPaneItem)vControl).Click += new RoutedEventHandler(aPanel.btn_click); //new EventHandler(aPanel.btn_click);
                                if (mField.GetIsRightPaneLink())
                                {
                                    rightPaneLinkItems.Add(vControl);
                                }
                                else
                                {
                                    leftPaneLinkItems.Add(vControl);
                                }
                            }
                        }
                    }
                }   //  for all fields
            }

            //  Tree Graphics Layout
            int AD_Tree_ID = 0;
            
            if (mTab.IsTreeTab())
            {
                var client = Utility.AEnv.GetDataServiceClient();
                //, Name
                string sql = "SELECT AD_Tree_ID FROM AD_Tree "
                + "WHERE AD_Client_ID=" + Utility.Envs.GetCtx().GetAD_Client_ID() + " AND AD_Table_ID=" + mTab.GetAD_Table_ID() + " AND IsActive='Y' AND IsAllNodes='Y' "
                + "ORDER BY IsDefault DESC, AD_Tree_ID";

                client.GetScalarCompleted += (sc, ec) =>
                {

                    if (ec.Error != null)
                    {
                        return;
                    }

                    try
                    {

                        AD_Tree_ID = Utility.Util.GetValueOfInt(ec.Result);

                        if (mTab.IsTreeTab() && AD_Tree_ID != 0)
                        {
                            tree = new TreeSearchPanel(windowNo, false, true);
                            //Set Style
                            if (mTab.GetTabNo() == 0)	//	initialize other tabs later
                            {
                                tree.InitTree(AD_Tree_ID);
                            }
                            //m_tree.addPropertyChangeListener(VTreePanel.NODE_SELECTION, this);
                            //vTreePanel.vTreeView.AfterSelect += new TreeViewEventHandler(vTreeView_AfterSelect);

                            treeContainer.Children.Add(tree);

                            tree.vTreeView.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(vTreeView_SelectedItemChanged);
                            LayoutRoot.ColumnDefinitions[0].Width = new GridLength(.4, GridUnitType.Star);
                            grsplSplitterV.Width = 3;
                            //treeContainer.Visibility = System.Windows.Visibility.Visible;
                        }
                        else    //  No Graphics - hide
                        {
                            //graphPanel.setPreferredSize(new Dimension(0, 0));
                            //splitPane.setDividerSize(0);
                            //                    splitPane.Panel1Collapsed = true;
                            //splitPane.setDividerLocation(0);
                        }
                    }
                    catch
                    {

                    }
                };
                client.GetScalarAsync(sql);
                client.CloseAsync();

                //AD_Tree_ID = MTree.GetDefaultAD_Tree_ID(Utility.Env.GetCtx().GetAD_Client_ID(), mTab.GetAD_Table_ID());
                // AD_Tree_ID = 121;

                ////  Set initial presentation
            }

            if (onlyMultiRow || !mTab.IsSingleRow())
                SwitchMultiRow();
            else
                SwitchSingleRow();

            ////if (_showMiniGrid)
            ////{
            ////    vPanel.BorderStyle = BorderStyle.FixedSingle;
            ////}

            AddDataStatusEventHandler();

            vTable.SelectionChanged += OnGridSelectionChanged;


            return true;
        }



        /// <summary>
        /// Add Event handler to table object model to show message and commit warning
        /// </summary>
        private void AddDataStatusEventHandler()
        {
            if (mTab != null)
            {
                mTab.GetTableObj().VetoableChange += new EventHandler(GridController_VetoableChange);
                mTab.GetTableObj().FireDataStatusEvent += new DataStatusEEventHandler(GridController_FireDataStatusEvent);
            }
        }

        /// <summary>
        /// Show messages in status bar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridController_FireDataStatusEvent(object sender, DataStatusEvent e)
        {
            _datastatusEvent = e;
            //FireDataStatusEvent();
            // aPanel.SetStatusLine(e);//._AD_Message + e._info, e._isError);
        }

        /// <summary>
        /// ask before sae if auto commit enabled
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridController_VetoableChange(object sender, EventArgs e)
        {
            if (!Utility.Envs.GetContext().IsAutoCommit(windowNo) || mTab.GetCommitWarning().Length > 0)
            {
                bool isWaiting = true;
                bool throwError = false;

                Dispatcher.BeginInvoke(delegate
                {

                    ShowMessage.AskMessage("SaveChanges?", true, mTab.GetCommitWarning()).Closed += (ss, ee) =>
                        {
                            if (((VAdvantage.Framework.Message)ss).DialogResult != null && ((VAdvantage.Framework.Message)ss).DialogResult.Value)
                            {
                                ;
                            }
                            else
                            {
                                throwError = true;
                            }
                            isWaiting = false;
                        };
                });
                //if (!ShowMessage.Ask("SaveChanges?", true, mTab.GetCommitWarning()))
                //{
                //    throw new Exception("UserDeniedSave");
                //}

                while (isWaiting)
                {
                    System.Threading.Thread.Sleep(10);
                }

                if (throwError)
                {
                    throw new Exception("UserDeniedSave");
                }
            }
        }

        /// <summary>
        /// tree After Select Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 

        void vTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            //    throw new NotImplementedException();
            //}
            //private void vTreeView_AfterSelect(object sender, TreeViewEventArgs e)
            //{

            VTreeNode node = e.NewValue as VTreeNode;

            if (isPostionSetting || node == null)
            {
                return;
            }


            if (node.Name != "0" && bindingSource.Count > 0)
            {
                //aPanel.blockEvent = true;
                //find postion of selected node in binding source
                findSelectedNode = false;

                int pos = bindingSource.Find(mTab.GetKeyColumnName(), node.Name);
                if (pos > -1)
                {
                    currentRowIndex = 0;
                    SetPostion(pos);
                }
                RequestFocusInWindow();
                findSelectedNode = true;
                //aPanel.blockEvent = false;
            }
        }

        /// <summary>
        ///	Activate Grid Controller.
        /// initilize treevirew controls if tab has 'hastree' propertyset to true
        /// </summary>
        public void Activate()
        {
            //Tree to be initiated on second/.. tab
            if (mTab == null)
            {
                return;
            }

            if (mTab.IsTreeTab() && mTab.GetTabNo() > 0)
            {
                int AD_Tree_ID = 0;
                if (mTab.GetTabLevel() > 0)	//	check previous tab for AD_Tree_ID
                {
                    String keyColumnName = mTab.GetKeyColumnName();
                    String treeName = "AD_Tree_ID";
                    if (keyColumnName.StartsWith("CM"))
                    {
                        if (keyColumnName.Equals("CM_Container_ID"))
                            treeName = "AD_TreeCMC_ID";
                        else if (keyColumnName.Equals("CM_CStage_ID"))
                            treeName = "AD_TreeCMS_ID";
                        else if (keyColumnName.Equals("CM_Template_ID"))
                            treeName = "AD_TreeCMT_ID";
                        else if (keyColumnName.Equals("CM_Media_ID"))
                            treeName = "AD_TreeCMM_ID";
                    }
                    AD_Tree_ID = Utility.Envs.GetContext().GetContextAsInt(windowNo, treeName);
                    log.Config(keyColumnName + " -> " + treeName + " = " + AD_Tree_ID);
                }
                if (AD_Tree_ID == 0)
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(delegate
                    {
                        AD_Tree_ID = MTree.GetDefaultAD_Tree_ID(Utility.Envs.GetContext().GetAD_Client_ID(),
                                                                mTab.GetAD_Table_ID());
                        if (tree != null && AD_Tree_ID > 0)
                        {
                            Dispatcher.BeginInvoke(() =>
                            tree.InitTree(AD_Tree_ID));
                        }
                    });
                }
                else
                {
                    if (tree != null)
                        tree.InitTree(AD_Tree_ID);
                }
            }
        }

        /// <summary>
        /// Set Tree Prpperties 
        /// </summary>
        private void SetTreeView()
        {
            //    vTreePanel = new VTreePanel();
            //    vTreePanel.Dock = DockStyle.Fill;
        }

        /// <summary>
        /// Switch to SingleRow Presentation
        /// </summary>
        public void SwitchSingleRow()
        {
            if (onlyMultiRow)
                return;
            //cardLayout.first(cardPanel);

            //vTable.TabStop = false;
            //vPanel.TabStop = true;

            grdMainArea.RowDefinitions[0].Height = new GridLength(1, GridUnitType.Star);
            if (_showMiniGrid)
            {
                vTable.IsMiniGrid = true;
                grsplSplitterH.Visibility = System.Windows.Visibility.Visible;
                // Grid.SetRow(vTable, 2);
                grdMainArea.RowDefinitions[2].Height = new GridLength(.6, GridUnitType.Star);
            }
            else
            {
                grdMainArea.RowDefinitions[2].Height = new GridLength(0);

                grsplSplitterH.Visibility = System.Windows.Visibility.Collapsed;
                vTable.Visibility = System.Windows.Visibility.Collapsed;
                //spltControlsPane.Panel2Collapsed = true;
            }
            singleRow = true;
            vPanelViewer.Visibility = System.Windows.Visibility.Visible;
            DynamicDisplay("");
            //spltControlsPane.Panel1Collapsed = false;
            //vPanel.BringToFront();

            //vPanel.requestFocus();
        }   //  switchSingleRow

        /// <summary>
        /// Switch to MultiRow Presentation
        /// </summary>
        public void SwitchMultiRow()
        {
            singleRow = false;
            //vTable.TabStop = true;
            //vPanel.TabStop = false;
            //spltControlsPane.Panel1Collapsed = true;
            //vTable.PaintGrid();

            grdMainArea.RowDefinitions[0].Height = new GridLength(0);
            grdMainArea.RowDefinitions[2].Height = new GridLength(1, GridUnitType.Star);
            if (_showMiniGrid)
            {


                vTable.IsMiniGrid = false;
                // Grid.SetRow(vTable, 0);
                //vTable.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
                //vTable.Dock = DockStyle.Fill;
            }
            else
            {
                vTable.Visibility = System.Windows.Visibility.Visible;
            }
            vPanelViewer.Visibility = System.Windows.Visibility.Collapsed;
            grsplSplitterH.Visibility = System.Windows.Visibility.Collapsed;
            //vTable.BringToFront();
        }

        /// <summary>
        ///Switch from single to multi & vice versa
        /// </summary>
        public void SwitchRowPresentation()
        {
            StopEditor(true);
            if (singleRow)
                SwitchMultiRow();
            else
                SwitchSingleRow();
        }

        /// <summary>
        ///Is Single Row presentation
        /// </summary>
        /// <returns>true if Single Row is displayed</returns>
        public bool IsSingleRow()
        {
            return singleRow;//&& !(vTable.IsMiniGrid && (vTable.f .Focused || vTable.HeaderClicked));
        }

        /// <summary>
        ///Stop Table & SR Editors and move focus to graphPanel
        /// </summary>
        /// <param name="saveValue">saveValue save value</param>
        public void StopEditor(bool manualSave)
        {
            ////  SingleRow - stop editors by changing focus
            //if (singleRow && !vTable.IsMiniGrid)
            //    vPanel.Select();
            //else
            //{
            //    if (manualSave || !vTable.IsGridSelection())
            //    {

            //        vTable.Parent.Parent.Parent.Select();
            //    }
            //    else
            //    {
            //        if (vTable.CurrentCell != null && vTable.CurrentCell.IsInEditMode)
            //            vTable.CurrentCell = null;
            //    }
            //    if (vTable.IsCurrentRowDirty)
            //        vTable.EndEdit();
            //}
        }

        /// <summary>
        /// load the records and return true if success
        /// </summary>
        /// <param name="onlyCurrentDays"></param>
        /// <param name="maxRows"></param>
        /// <param name="created"></param>
        /// <returns></returns>
        /// 

        System.ComponentModel.BackgroundWorker worker = null;

        public bool query(int onlyCurrentDays,
        int maxRows, bool created)
        {
            bool success = false;
            //isPostionSetting = true;
            ////  start loading while building screen
            currentRowIndex = -1;

            vPanel.DataContext = null;
            vTable.ItemsSource = null;


            worker = new System.ComponentModel.BackgroundWorker();
            worker.WorkerSupportsCancellation = true;

            //new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            // {


            worker.DoWork += (sender, e) =>
            {
                e.Result = mTab.PrepareQuery(onlyCurrentDays, maxRows, created);
            };

            //    this.Dispatcher.BeginInvoke(delegate
            //    {
            //         aPanel.ShowWindow();
            //   // success = (bool)e.Result;
            //    bool setPos = false;

            //    if (success && mTab.GetDataTable() != null)
            //    {
            //        bindingSource = mTab.GetDataTable();
            //        bool parentValid = true;
            //        String lc = mTab.GetLinkColumnName();
            //        String lcValue = Utility.Env.GetCtx().GetContext(windowNo, lc);
            //        if (lc.Length > 0 && lcValue.Length == 0)
            //        {
            //            parentValid = false;
            //        }
            //        //Set Initial record
            //        //  Set initial record
            //        if (bindingSource.Count == 0)
            //        {
            //            //	Automatically create New Record, if none & tab not RO
            //            if (!mTab.IsReadOnly() && !aPanel.loading &&
            //            (Utility.Env.GetCtx().IsAutoNew(windowNo) || mTab.IsQueryNewRecord()) && parentValid )
            //            {
            //                if (mTab.CheckDataNew())
            //                {
            //                    aPanel.AddNewRow(false);
            //                }
            //                else
            //                {
            //                    //aPanel.SetButtons(false, false);
            //                    //aPanel.SetNavigateButtons();
            //                }
            //            }
            //            else
            //            {

            //                aPanel.SetButtons(false, true);
            //                //aDelete.SetEnabled(false);
            //            }

            //        }

            //        vTable.ItemsSource = bindingSource;
            //        if (bindingSource.Count > 0)
            //        {
            //            currentRow = (DataUtil.DataObject)bindingSource[0];
            //            setPos = true;
            //            ignoreAutoSave = true;
            //            SetPostion(0);
            //            ignoreAutoSave = false;

            //        }
            //    }


            //    aPanel.SetBusy(false, true);

            //    });


            //})).Start();

            //};

            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (aPanel != null)
                {
                    aPanel.ShowWindow();
                    aPanel.OnLoad();
                }


                success = (bool)e.Result;
                bool setPos = false;


                bool isNewRowInserting = false;

                if (success && mTab.GetDataTable() != null)
                {

                    SetBindingSource(mTab.GetDataTable());

                    isNewRowInserting = CheckInsertNewRow();
                    if (!isNewRowInserting)
                    {
                        if (OnManualRowInserting != null)
                        {
                            OnManualRowInserting(this, EventArgs.Empty);
                        }
                    }

                    vTable.ItemsSource = bindingSource;

                    //ICollectionView collectionView = new PagedCollectionView(bindingSource);
                    //vTable.ItemsSource = collectionView;

                    //vTable.ItemsSource = bindingSource;

                    if (bindingSource.Count > 0)
                    {

                        //currentRow = (DataUtil.DataObject)bindingSource[0];
                        setPos = true;
                        ignoreAutoSave = true;
                        SetPostion(0);
                        ignoreAutoSave = false;

                    }
                }

                if (!isNewRowInserting)
                {
                    SetBusy(false, true);
                }

            };
            worker.RunWorkerAsync();
            SetBusy(true, true);
            if (success && mTab.GetDataTable() != null)
            {

            }

            return success;
        }

        private void SetBindingSource(IList iList)
        {
            if (bindingSource != null)
            {
                bindingSource.Sorting -= new EventHandler<CustomSortEventArgs>(bindingSource_Sorting);
                bindingSource.Sorted -= new EventHandler<SortedEventArgs>(bindingSource_Sorted);
                bindingSource = null;
            }
            bindingSource = new BindingSource(mTab.GetDataTable());
            bindingSource.Sorting += new EventHandler<CustomSortEventArgs>(bindingSource_Sorting);
            bindingSource.Sorted += new EventHandler<SortedEventArgs>(bindingSource_Sorted);
        }

        void bindingSource_Sorted(object sender, SortedEventArgs e)
        {
            ignoreAutoSave = true;
            SetPostion(0);
            vTable.PaintRow();
            ignoreAutoSave = false;
            //RequestFocusInWindow();
        }

        void bindingSource_Sorting(object sender, CustomSortEventArgs e)
        {

            if (vTable == null || vTable.Columns.Count < 1)
            {
                return;
            }

            if (aPanel != null && aPanel.NeedSave(true))
            {
                aPanel.UndoChanges();
            }

            var col = (from c in vTable.Columns
                       where ((IDataGridColumn)c).DataPropertyName == e.Sort.PropertyName
                       select c).SingleOrDefault();

            Lookup _lookup = null;

            if (col is IDataGridColumn)
            {
                int d = ((IDataGridColumn)col).Field.GetDisplayType();
                if (DisplayType.IsID(d) || DisplayType.List == d)
                {
                    _lookup = ((IDataGridColumn)col).Field.GetLookup();
                    e.IsCustom = true;
                }
            }

            if (e.IsCustom)
            {
                List<Object> rowSource = new List<Object>(e.SortedList as List<Object>);

                Dictionary<int, string> sDic = new Dictionary<int, string>();
                String txt = "";

                for (int i = 0; i < rowSource.Count; i++)
                {
                    DataUtil.DataObject obj = (DataUtil.DataObject)rowSource[i];

                    object value = obj.GetFieldValue(e.Sort.PropertyName);

                    FrameworkElement el = vTable.Columns.Last().GetCellContent(obj);


                    if (el == null)
                    {
                        if (_lookup != null && value != null)
                        {
                            if (_lookup.IsValidated())
                            {
                                NamePair nm = _lookup.GetFromValidatedList(value);

                                if (nm != null)
                                {
                                    txt = nm.GetName();
                                }

                                else
                                {
                                    if (_lookup is MLookup)
                                    {
                                        nm = ((MLookup)_lookup)._lookupDirectAll[value];
                                        if (nm != null)
                                        {
                                            txt = nm.GetName();
                                        }
                                    }
                                }

                            }
                            else
                            {
                                txt = _lookup.GetDisplayFromList(value);
                            }
                        }
                    }
                    else
                    {
                        DataGridRow row1 = DataGridRow.GetRowContainingElement(el.Parent as FrameworkElement);
                        if (row1 != null)
                        {
                            FrameworkElement fe = col.GetCellContent(row1);
                            if (fe is TextBlock)
                            {
                                txt = ((TextBlock)fe).Text;
                            }


                        }
                    }
                    sDic[i] = txt;
                    txt = "";
                }

                e.SortedList.Clear();

                if (e.Sort.Direction == ListSortDirection.Ascending)
                {
                    var items = from k in sDic.Keys
                                orderby sDic[k]
                                select k;
                    //var items = from t in vTable.Rows.Cast<DataGridViewRow>()
                    //            orderby t.Cells[lastCol.Index].FormattedValue
                    //            select t.Index;
                    foreach (int k in items)
                    {
                        e.SortedList.Add(rowSource[k]);
                    }
                }
                else
                {
                    var items = from k in sDic.Keys
                                orderby sDic[k] descending
                                select k;
                    //var items = from t in vTable.Rows.Cast<DataGridViewRow>()
                    //            orderby t.Cells[lastCol.Index].FormattedValue
                    //            select t.Index;
                    foreach (int k in items)
                    {
                        e.SortedList.Add(rowSource[k]);
                    }
                }
            }
        }


        //public static SolidColorBrush GetColorFromHexa(string hexaColor)
        //{
        //    return new SolidColorBrush(
        //        Color.FromArgb(
        //            Convert.ToByte(hexaColor.Substring(1, 2), 16),
        //            Convert.ToByte(hexaColor.Substring(3, 2), 16),
        //            Convert.ToByte(hexaColor.Substring(5, 2), 16),
        //            Convert.ToByte(hexaColor.Substring(7, 2), 16)
        //        )
        //    );
        //}


        public bool GetDataGrid(VGridPanel panel, Grid LayoutGrid, int onlyCurrentDays, int maxRows, bool created, int RC_View_ID, bool firstTime)
        {
            return GetDataGrid(panel, LayoutGrid, onlyCurrentDays, maxRows, created, RC_View_ID, firstTime, 0);
        }

        public bool GetDataGrid(VGridPanel panel, Grid LayoutGrid, int onlyCurrentDays, int maxRows, bool created, int RC_View_ID, bool firstTime,int wait)
        {
            BusyIndicator busy = new BusyIndicator();
            bool success = false;

            currentRowIndex = -1;

            panel.PanelData(LayoutGrid, firstTime);
            panel.AddControl(busy);
            busy.IsBusy = true;

            //dTable.ItemsSource = null;
            //dTable.DataContext = null;
            //dTable.Visibility = System.Windows.Visibility.Collapsed;

            vPanel.DataContext = null;
            vTable.ItemsSource = null;
            //vTable.Background = new SolidColorBrush(Colors.White);
            //vTable.BorderBrush = new SolidColorBrush(Colors.White);
            //vTable.BorderThickness = new Thickness(0);
            vTable.ColumnHeaderStyle = Application.Current.Resources["DataGridColumnHeaderStyleSL"] as Style;
            vTable.RowHeaderStyle = Application.Current.Resources["DataGridRowHeaderStyleSL"] as Style;
            vTable.ColumnHeaderHeight = 25;
            vTable.RowHeight = 23;
            vTable.BorderThickness = new Thickness(0);
            vTable.BorderBrush = new SolidColorBrush(Colors.DarkGray);
            vTable.MinColumnWidth = 100;
            vTable.ColumnWidth = new DataGridLength(1, DataGridLengthUnitType.SizeToCells);
            vTable.GridLinesVisibility = DataGridGridLinesVisibility.None;
            vTable.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;

            //vTable.AlternatingRowBackground = GetColorFromHexa("#eaeaea");
            //vTable.Foreground = GetColorFromHexa("#595959");
            //vTable.Background = GetColorFromHexa("#f6f8fa");

            worker = new System.ComponentModel.BackgroundWorker();
            worker.WorkerSupportsCancellation = true;
            List<int> visibleFields = new List<int>();
            worker.DoWork += (sender, e) =>
            {
               // System.Threading.Thread.Sleep(2000 * wait);
                mTab.IsThroughRoleCenter(true);
                e.Result = mTab.PrepareQuery(onlyCurrentDays, maxRows, created);
                //mTab.GetFieldDetail(
            };


            worker.RunWorkerCompleted += (sender, e) =>
            {

                busy.IsBusy = false;
                //LayoutGrid.Children.Remove(busy);
                if (aPanel != null)
                {
                    aPanel.ShowWindow();
                    aPanel.OnLoad();
                }


                success = (bool)e.Result;
                bool setPos = false;


                bool isNewRowInserting = false;

                if (success && mTab.GetDataTable() != null)
                {
                    //ndingSource = new  null;// mTab.GetDataTable();
                    SetBindingSource(mTab.GetDataTable());

                    //isNewRowInserting = CheckInsertNewRow();
                    vTable.IsReadOnly = true;
                    vTable.SupressRowPaint = true;
                    vTable.ItemsSource = bindingSource;
                    vTable.LoadingRow += new EventHandler<DataGridRowEventArgs>(vTable_LoadingRow);
                    panel.SetTotalPage(mTab.GetTotalRowCount());
                    busy.IsBusy = false;
                    panel.RemoveControl(busy);
                    //dTable.Visibility = System.Windows.Visibility.Visible;
                    //panel.SetPager(bindingSource);

                    //if (bindingSource.Count > 0)
                    //{
                    //    //currentRow = (DataUtil.DataObject)bindingSource[0];
                    //    //setPos = true;
                    //    //ignoreAutoSave = true;
                    //    //SetPostion(0);
                    //    //ignoreAutoSave = false;
                    //}
                }

                if (!isNewRowInserting)
                {
                    SetBusy(false, true);
                }

            };
            worker.RunWorkerAsync();
            SetBusy(true, true);
            if (success && mTab.GetDataTable() != null)
            {

            }

            return success;
        }

        void vTable_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            VDataGrid dg = (sender as VDataGrid);
            DataGridRow dgr = e.Row;

            PopupMenu infoWin = new PopupMenu();
            PopupMenuItem mnu = new PopupMenuItem("Images/Zoom32.png", Msg.GetMsg(Envs.GetCtx(), "Zoom"), null);
            mnu.Name = "Zoom";
            mnu.Click += new RoutedEventHandler(mnu_Click);
            infoWin.AddItem(mnu);

            infoWin.AddTrigger(TriggerTypes.RightClick, dgr);
        }

        void mnu_Click(object sender, RoutedEventArgs e)
        {
            DataUtil.DataObject dob = vTable.SelectedItem as VAdvantage.DataUtil.DataObject;
            AWindow win = new AWindow();
            int AD_Window_ID = 0;

            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (o, ev) =>
                {
                    AD_Window_ID = mTab.GetAD_Window_ID();

                };

            bgw.RunWorkerCompleted += (o, ev) =>
                {
                    win.InitWindow(AD_Window_ID, Query.GetEqualQuery(mTab.GetTableName() + "_ID", dob.GetFieldValue(mTab.GetTableName().ToUpper() + "_ID")));
                    win.ShowWindow();
                    Utility.Envs.SetBusyIndicator(false);
                };

            bgw.RunWorkerAsync();
        }

        private bool CheckInsertNewRow()
        {
            if (aPanel == null)
                return false;

            bool parentValid = true;
            String lc = mTab.GetLinkColumnName();
            String lcValue = Utility.Envs.GetCtx().GetContext(windowNo, lc);
            if (lc.Length > 0 && lcValue.Length == 0)
            {
                parentValid = false;
            }
            //Set Initial record
            //  Set initial record
            if (bindingSource.Count == 0)
            {
                //	Automatically create New Record, if none & tab not RO
                if (!mTab.IsReadOnly() && !aPanel.loading &&
                (Utility.Envs.GetCtx().IsAutoNew(windowNo) || mTab.IsQueryNewRecord()) && parentValid)
                {
                    if (mTab.CheckDataNew())
                    {
                        aPanel.AddNewRow(false);
                        return true;
                    }
                    else
                    {
                        //aPanel.SetButtons(false, false);
                        //aPanel.SetNavigateButtons();
                    }
                }
                else
                {

                    aPanel.SetButtons(false, true);
                    //aDelete.SetEnabled(false);
                }

            }
            return false;
        }

        public void SetBusy(bool busy, bool focus)
        {
            if (aPanel != null)
            {
                aPanel.SetBusy(busy, focus);
            }
            if (_iBusy != null)
            {
                _iBusy.SetBusy(busy);
            }
        }

        bool ignoreAutoSave = false;

        /// <summary>
        /// Return Row Count
        /// </summary>
        /// <returns></returns>
        //public int RowCount()
        //{
        //    return this.BindingSource.Count;
        //}

        /// <summary>
        /// Set postion(navigate) of bindingsource
        /// </summary>
        /// <param name="row"></param>
        /// 
        int currentRowIndex = -1;

        public void SetCurrentRowIndex(int row)
        {
            currentRowIndex = row;

        }


        bool _gridIndexSetting = false;

        public void SetPostion(int row)
        {
            _gridIndexSetting = true;
            // isPostionSetting = true;
            //if(!singleRow)
            ////{
            ////    vTable.SetGridSelection(true);
            ////}
            //StopEditor(false);
            currentRowIndex += row;
            if (row == 0 || currentRowIndex <= 0)
            {
                currentRowIndex = 0;

            }
            else if (row >= bindingSource.Count - 1 || currentRowIndex >= bindingSource.Count - 1)
            {
                currentRowIndex = bindingSource.Count - 1;

            }

            SettingCurrentPostionData();
            vTable.SelectedIndex = currentRowIndex;
            _gridIndexSetting = false;
        }

        internal void NavigatePage(bool isPageUp, int curPage)
        {
            if (isPageUp)
            {
                mTab.GetTableObj().SetCurrentPage(curPage--);
            }
            else
            {
                mTab.GetTableObj().SetCurrentPage(curPage++);
            }


        }

        public void SettingCurrentPostionData()
        {
            if (!ignoreAutoSave && (aPanel != null && aPanel.NeedSave(true)))
            {
                aPanel.PositionChanging();
                return;
            }
            SetCurrentPostionData();
        }

        public void SetCurrentPostionData()
        {
            if (bindingSource == null)
                return;
            currentRow = (DataUtil.DataObject)bindingSource[currentRowIndex];
            //vPanel.DataContext = null;
            vPanel.DataContext = currentRow;

            if (TreePaneLeftLinks != null)
            {
                TreePaneLeftLinks.DataContext = currentRow;
                TreePaneRightLinks.DataContext = currentRow;
            }
            // currentRow.EndEdit();
            //mTab.CurrentRowData = currentRow;
            //SetSelectedTreeNode(mTab.GetRecord_ID());
            OnPositionChanged();
        }

        void OnGridSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_gridIndexSetting || (currentRowIndex == vTable.SelectedIndex))
            {
                return;
            }

            if (vTable.SelectedIndex < 0 && bindingSource != null && bindingSource.Count > 0)
            {
                //currentRowIndex = 0;
                vTable.SelectedIndex = currentRowIndex;
            }

            currentRowIndex = vTable.SelectedIndex;
            SettingCurrentPostionData();
        }

        //public BindingSource GetDataSource()
        //{
        //    return this.BindingSource;
        //}
        ///// <summary>
        ///// Set Current Row Data;
        ///// </summary>_po
        ///// 
        //public void SetCurrentRowData()
        //{
        //    mTab.CurrentRowData = this.BindingSource.Current as DataRowView;
        //    mTab.CurrentRow = this.BindingSource.Position;
        //    SetSelectedTreeNode();
        //    FireDataStatusEvent();
        //}

        /// <summary>
        /// Add new Row
        /// </summary>
        /// <returns></returns>
        /// 
        public bool AddNewRow(bool copy)
        {
            return AddNewRow(copy, false);
        }
        public bool AddNewRow(bool copy, bool toogle)
        {
            DataUtil.DataObject sourceRow = null;
            isPostionSetting = true;
            _gridIndexSetting = true;
            /* remove Sort Mode of binding Source*/
            //this.BindingSource.RemoveSort();
            if (copy)
            {
                sourceRow = mTab.CurrentRowDataObject;
            }

            //bindingSource.SortDescriptions.Clear(); // Clear Sorting

            //this.Select();

            // DataUtil.DataObject dRow = Activator.CreateInstance(bindingSource.GetType().GetGenericArguments()[0]) as DataUtil.DataObject;
            //if (bindingSource == null)
            //{
            //    return true;
            //}
            object row = bindingSource.AddNew();

            DataUtil.DataObject dRow = row as DataUtil.DataObject;

            mTab.NewRow = true;
            mTab.CurrentRowDataObject = dRow;

            BackgroundWorker bgw = new BackgroundWorker();


            bgw.DoWork += (sd, ed) =>
            {
                Utility.Envs.SetThreadCulture();
                ed.Result = mTab.DataNew(copy, sourceRow);
            };

            bgw.RunWorkerCompleted += (sc, ec) =>
            {
                bindingSource.CommitNew();
                if (!(bool)ec.Result)
                {
                    this.bindingSource.Remove(dRow);
                    dRow = null;
                    mTab.CurrentRowDataObject = currentRow;
                }
                else
                {
                    //bindingSource.Add(dRow);
                    //bindingSource.CommitNew();
                    currentRow = dRow;
                    currentRowIndex = bindingSource.Count - 1;
                    vPanel.DataContext = currentRow;
                    vTable.SelectedIndex = currentRowIndex;
                }
                mTab.CurrentRow = currentRowIndex;
                isPostionSetting = false;
                _gridIndexSetting = false;
                mTab.NewRow = false;
                sourceRow = null;
                FireDataStatusEvent();

                if (!mTab.GetTableObj().isMultipleProduct)
                {
                    aPanel.AfterAddNewRow((bool)ec.Result);
                }

                if (OnNewRowInserted != null)
                {
                    OnNewRowInserted(this, new NewEventArgs((bool)ec.Result));
                }

            };
            bgw.RunWorkerAsync();

            if (toogle && !singleRow)
            {
                SwitchSingleRow();
            }

            return true;
            // DynamicDisplay("");
        }

        //only for Multipledelete
        public event EventHandler DeleteCompleted;

        /// <summary>
        /// Delete Row From Binding Source And from database
        /// </summary>
        /// 

        public void DeleteDataRow()
        {
            isPostionSetting = true;
            _gridIndexSetting = true;

            worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                e.Result = mTab.DataDelete(currentRowIndex);
            };

            worker.RunWorkerCompleted += (sender, e) =>
            {
                if ((bool)e.Result)
                {
                    this.bindingSource.Remove(currentRow);
                    //this.BindingSource.EndEdit();
                    RowChanged(false, mTab.GetRecord_ID());
                    if (currentRowIndex >= bindingSource.Count)
                    {
                        currentRowIndex = bindingSource.Count - 1;
                    }

                    if (currentRowIndex >= 0)
                    {
                        currentRow = bindingSource[currentRowIndex] as DataUtil.DataObject;
                        mTab.CurrentRowDataObject = currentRow;
                        vPanel.DataContext = currentRow;
                        vTable.SelectedIndex = currentRowIndex;

                        // DynamicDisplay("");

                        SetSelectedTreeNode();
                    }
                    else
                    {
                        currentRow = null;
                        vTable.DataContext = null;
                        vPanel.DataContext = null;
                        mTab.CurrentRowDataObject = null;
                    }
                    DynamicDisplay("");
                }
                isPostionSetting = false;
                _gridIndexSetting = false;
                FireDataStatusEvent();

                if (DeleteCompleted != null)
                {
                    DeleteCompleted(this, new DeleteEventArgs((bool)e.Result));
                }
                else
                {
                    vTable.PaintRow();//refresh row index
                    SetBusy(false, true);
                }
            };
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// editing
        /// </summary>
        public void SetValueChanged()
        {
            mTab.GetTableObj().SetChanged();
            FireDataStatusEvent();
        }

        /// <summary>
        /// Undo Changes of row
        /// </summary>
        public void UndoChanges(bool isNewRow)
        {
            isPostionSetting = true;
            _gridIndexSetting = true;
            //vTable.TabStop = false;
            mTab.GetTableObj().DataIgnore();
            try
            {
                if (isNewRow && this.bindingSource.Count == 1)
                {
                    currentRowIndex = -1;
                    this.bindingSource.Clear();
                    currentRow = null;
                    vPanel.DataContext = null;
                    mTab.CurrentRowDataObject = null;
                    mTab.CurrentRow = -1;

                }
                else if (isNewRow)
                {

                    bindingSource.CancelNew();
                    bindingSource.Remove(currentRow);
                    currentRowIndex = bindingSource.Count - 1;
                    currentRow = (DataUtil.DataObject)bindingSource[currentRowIndex];
                    mTab.CurrentRowDataObject = currentRow;
                    mTab.CurrentRow = currentRowIndex;
                    vPanel.DataContext = currentRow;
                    vTable.SelectedIndex = currentRowIndex;

                    //((DataRowView)this.BindingSource.Current).Row.Table.RejectChanges();
                }
                else
                {
                    currentRow.CancelEdit();
                    mTab.CurrentRowDataObject = currentRow;
                    //((DataRowView)this.BindingSource.Current).Row.RejectChanges();
                }
                //  this.BindingSource.ResetBindings(false);
                // LateBinding();
                //this.BindingSource.EndEdit();
                //if (isNewRow)
                //{

                // }
                if (bindingSource.Count > 0)
                {

                }
                //ReDrawCurrentRow();
                DynamicDisplay("");
                // isPostionSetting = false;
                //if (vTable.IsCurrentRowDirty)
                //    vTable.CancelEdit();
                //StopEditor(false);
            }
            catch
            {
            }
            isPostionSetting = false;
            _gridIndexSetting = false;
            FireDataStatusEvent();
        }

        ///// <summary>
        ///// Save Row Data
        ///// </summary>
        ///// <param name="manualSave"></param>
        ///// <returns></returns>
        public bool SaveData(bool manualSave)
        {
            // System.ComponentModel.BackgroundWorker saveWorker = new System.ComponentModel.BackgroundWorker();
            bool retValue = false;
            //saveWorker.DoWork += (sender, e) =>
            //  {
            retValue = mTab.DataSave(manualSave);
            //  };

            // saveWorker.RunWorkerCompleted += (sender, e) =>
            //  {

            if (retValue)
            {
                //this.BindingSource.EndEdit();
                ////this.bindingSource.CommitNew();
                //this.bindingSource.CommitEdit();
                // RowChanged(true, mTab.GetRecord_ID());
                if (manualSave)
                {
                    //SetSelectedTreeNode();
                }
                //else (
                //{
                //    ReDrawCurrentRow();
                //}
            }
            else
            {
                if (!manualSave)
                {
                    currentRow.CancelEdit();
                }
            }

            //if (!manualSave)
            //{
            //    SetCurrentPostionData();
            //}
            FireDataStatusEvent();
            //aPanel.AfterSave(retValue, manualSave);
            // };
            // saveWorker.RunWorkerAsync();
            return retValue;
        }


        /// <summary>
        /// Class To Handle multisave eventargs
        /// </summary>
        internal class MultiSaveEventArgs : EventArgs
        {
            public bool IsSaved
            {
                get;
                set;
            }
            internal MultiSaveEventArgs(bool isSaved)
            {
                IsSaved = isSaved;
            }

        }

        internal event EventHandler InsertCompleted;

        ///// <summary>

        ///// Save Row Data
        ///// </summary>
        ///// <param name="manualSave"></param>
        ///// <returns></returns>
        public bool SaveData(bool manualSave, bool isMultiSave)
        {
            System.ComponentModel.BackgroundWorker saveWorker = new System.ComponentModel.BackgroundWorker();
            bool retValue = true;
            saveWorker.DoWork += (sender, e) =>
              {
                  retValue = mTab.DataSave(manualSave);
              };

            saveWorker.RunWorkerCompleted += (sender, e) =>
             {

                 if (retValue)
                 {
                     //this.BindingSource.EndEdit();
                     RowChanged(true, mTab.GetRecord_ID());
                     if (manualSave)
                     {
                         SetSelectedTreeNode();
                     }
                 }
                 else
                 {
                     if (!manualSave)
                     {
                         currentRow.CancelEdit();
                     }
                 }

                 //if (!manualSave)
                 //{
                 //    SetCurrentPostionData();
                 //}
                 FireDataStatusEvent();
                 if (InsertCompleted != null)
                 {
                     InsertCompleted(this, new MultiSaveEventArgs(retValue));
                 }
                 //aPanel.AfterSave(retValue, manualSave);
             };
            saveWorker.RunWorkerAsync();
            return retValue;
        }

        ///// <summary>
        ///// Refresh  single Row
        ///// </summary>
        public void DataRefreshRow()
        {
            mTab.DataRefresh();
            FireDataStatusEvent();
        }

        /// <summary>
        /// Refresh All Data
        /// </summary>
        public void DataRefreshAll()
        {
            isPostionSetting = true;
            _gridIndexSetting = true;
            //Find Key id of record
            vPanel.DataContext = null;
            vTable.ItemsSource = null;
            object keyID = mTab.GetRecord_ID();

            if (worker != null && worker.IsBusy)
            {
                return;
            }
            worker = new System.ComponentModel.BackgroundWorker();
            worker.WorkerSupportsCancellation = true;

            worker.DoWork += (sender, e) =>
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                }
                mTab.GetTableObj().DataRefreshAll();

            };

            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Cancelled)
                {
                    return;
                }
                //mTab.IsWaiting();
                mTab.LoadComplte();
                // if (mTab.GetDataTable() != null)
                // {
                SetBindingSource(mTab.GetDataTable());
                //this.bindingSource = new BindingSource(mTab.GetDataTable()) ;
                if (this.bindingSource.Count > 0)
                {
                    if ((currentRow == null && currentRowIndex == -1) || ((int)keyID) == -1)
                    {
                        currentRowIndex = 0;
                        currentRow = bindingSource[0] as DataUtil.DataObject;
                    }

                    /* Set position to Last Selected record*/
                    else
                    {
                        if (keyID.Equals(currentRow.GetFieldValue(mTab.GetKeyColumnName().ToUpper())))
                        {
                            if (bindingSource.Count > currentRowIndex)
                            {
                                currentRow = bindingSource[currentRowIndex] as DataUtil.DataObject;
                            }
                            else
                            {
                                currentRowIndex = 0;
                                currentRow = bindingSource[currentRowIndex] as DataUtil.DataObject;
                            }
                        }

                        else
                        {
                            int index = -1;
                            for (int i = 0; i < bindingSource.Count; i++)
                            {
                                if (keyID.Equals(((DataUtil.DataObject)bindingSource[0]).GetFieldValue(mTab.GetKeyColumnName().ToUpper())))
                                {
                                    index = i;
                                    break;
                                }
                            }

                            if (index != -1)
                            {
                                currentRowIndex = index;
                                currentRow = bindingSource[currentRowIndex] as DataUtil.DataObject;
                            }
                        }

                    }
                    mTab.CurrentRow = currentRowIndex;
                    mTab.CurrentRowDataObject = currentRow;
                    vTable.ItemsSource = bindingSource;
                    vTable.SelectedIndex = currentRowIndex;
                    vPanel.DataContext = currentRow;

                    DynamicDisplay("");

                    ////check worker thread is running
                    //if (t.IsAlive)
                    //{
                    //    //if yes join with main static thread
                    //    t.Join();
                    //    t = null;
                    //}
                    //if (!singleRow)
                    //    vTable.Invalidate();
                }
                // }

                isPostionSetting = false;
                _gridIndexSetting = false;
                FireDataStatusEvent();
                SetBusy(false, true);

            };

            worker.RunWorkerAsync();




        }

        ///// <summary>
        /////Row Changed - synchronize with Tree
        ///// </summary>
        ///// <param name="save"></param>
        ///// <param name="keyID">true the row was saved (changed/added), false if the row was deleted</param>
        //public void RowChanged(bool save, int keyID)
        //{
        //    if (vTreePanel == null || keyID <= 0)
        //        return;
        //    String name = mTab.GetValue("Name").ToString();
        //    String description = (string)mTab.GetValue("Description");
        //    bool? isSummary = (bool?)mTab.GetValue("IsSummary");
        //    bool summary = isSummary != null && isSummary.Value;
        //    String imageIndicator = (string)mTab.GetValue("Action");  //  Menu - Action

        //    vTreePanel.NodeChanged(save, keyID, name, description, summary, imageIndicator);
        //}   //  rowChanged


        ///// <summary>
        ///// 
        ///// </summary>
        ///// <returns></returns>
        ////public TableLayoutPanel table()
        ////{
        ////    return vPanel.GetTable();
        ////}

        ///// <summary>
        ///// Show and Hide Control depend on dynamic display logic
        ///// </summary>
        ///// <param name="col"></param>
        public void DynamicDisplay(string col)
        {
            // return;
            if (mTab == null)
                return;
            if (!mTab.IsOpen())
                return;

            if (vTable != null)
            {
                vTable.PaintRow(vTable.SelectedItem);
            }

            if (!singleRow)
            {
                DynamicDisplaySpecial(col);
                return;
            }
            //vTable.SuspendLayout();

            // TimeSpan t1 = DateTime.Now.TimeOfDay;

            // vPanel.GetTable().SuspendLayout();
            try
            {
                if (col != "")
                {
                    GridField changedField = mTab.GetField(col);
                    String columnName = changedField.GetColumnName();
                    List<GridField> dependants = mTab.GetDependantFields(columnName);
                    //log.config("(" + m_mTab.toString() + ") "
                    //	+ columnName + " - Dependents=" + dependants.size());
                    //	No Dependents and no Callout - Set just Background
                    if (dependants.Count == 0 && changedField.GetCallout().Length > 0)
                    {
                        // List<Control> comp = currentTab.GetControls();
                        for (int i = 0; i < vPanel.allControls.Count; i++)
                        {
                            //if (columnName.Equals(vPanel.allControls[i].Name))
                            //{
                            // vPanel.allControls[i].BackColor = Color.LightSkyBlue;
                            //ve.setBackground( changedField.isError() );
                            break;
                            //}
                        }
                        return;
                    }
                }

                //  complete single row re-display
                bool noData = mTab.GetRowCount() == 0;
                //log.config(m_mTab.toString() + " - Rows=" + m_mTab.getRowCount());
                //  All Components in vPanel (Single Row)
                //Control.ControlCollection comps = currentTab.FieldPanal.Controls;
                //Control[] comps = currentTab.GetControls().ToArray();
                for (int i = 0; i < vPanel.allControls.Count; i++)
                {
                    IControl comp = vPanel.allControls[i];
                    //IControl compI = (IControl)comp;
                    String columnName = comp.GetName();

                    if (columnName.StartsWith("lbl"))
                    {
                        columnName = columnName.Substring(3);
                    }
                    GridField mField = mTab.GetField(columnName);
                    if (mField != null)
                    {
                        if (mField.IsDisplayed(true))		//  check context
                        {
                            bool? vis = (bool?)((Control)comp).Tag;
                            if (!comp.Visible && (vis == null || (bool)vis))
                            {
                                comp.Visible = true;
                            }
                            if (comp is IControl && !((Control)comp is VLabel))
                            {
                                IControl compI = (IControl)comp;
                                //VEditor ve = (VEditor)comp;
                                if (!noData)
                                {//*work on read only
                                    bool rw = mField.IsEditable(true);	//  r/w - check Context
                                    compI.SetReadOnly(!rw);
                                }
                                else
                                {
                                    compI.SetReadOnly(true);
                                    //	log.log(Level.FINEST, "RW=" + rw + " " + mField);
                                    //((IControl)comp).SetBackGround(mField.IsError());
                                }
                            }
                        }
                        else if (comp.Visible)
                        {
                            comp.Visible = false;
                        }

                    }
                    //}
                }
            }
            catch
            {
            }
            // vPanel.GetTable().ResumeLayout(false);
            //vPanel.GetTable().PerformLayout();

            // MessageBox.Show((DateTime.Now.TimeOfDay - t1).ToString());
        }


        /// <summary>
        /// show hide Pane Link(left-Right)  on dynamic display logic
        /// Special case handle for (links)
        /// /* MultirowVeiw force display*/
        /// </summary>
        /// <param name="col"></param>
        public void DynamicDisplaySpecial(string col)
        {
            try
            {
                //  complete single row re-display
                bool noData = mTab.GetRowCount() == 0;
                //log.Config(m_mTab.toString() + " - Rows=" + m_mTab.getRowCount());
                //  All Components in vPanel (Single Row)
                //Control.ControlCollection comps = currentTab.FieldPanal.Controls;
                //Control[] comps = currentTab.GetControls().ToArray();
                for (int i = 0; i < vPanel.allLinkControls.Count; i++)
                {
                    IControl comp = vPanel.allLinkControls[i];
                    //IControl compI = (IControl)comp;
                    String columnName = comp.GetName();

                    if (columnName.StartsWith("lbl"))
                    {
                        columnName = columnName.Substring(3);
                    }
                    GridField mField = mTab.GetField(columnName);
                    if (mField != null)
                    {
                        if (mField.IsDisplayed(true))		//  check context
                        {
                            bool? vis = (bool?)((Control)comp).Tag;
                            if (!comp.Visible && (vis == null || (bool)vis))
                            {
                                comp.Visible = true;
                            }
                            if (comp is IControl && !((Control)comp is VLabel))
                            {
                                IControl compI = (IControl)comp;
                                //VEditor ve = (VEditor)comp;
                                if (!noData)
                                {//*work on read only
                                    bool rw = mField.IsEditable(true);	//  r/w - check Context
                                    compI.SetReadOnly(!rw);
                                }
                                else
                                {
                                    compI.SetReadOnly(true);
                                    //	log.log(Level.FINEST, "RW=" + rw + " " + mField);
                                    //((IControl)comp).SetBackGround(mField.IsError());
                                }
                            }
                        }
                        else if (comp.Visible)
                        {
                            comp.Visible = false;
                        }

                    }
                    //}
                }
            }
            catch
            {
            }




        }

        ///// <summary>
        ///// Set Selected Node Of Tree
        ///// </summary>
        ///// <param name="id"></param>
        public void SetSelectedTreeNode()
        {
            if (tree != null && findSelectedNode)
            {
                int id = mTab.GetRecord_ID();
                if (id <= 0)
                {
                    return;
                }
                //Condition to block tree after select event 
                isPostionSetting = true;
                object myTreeNode = null;


                //System.Collections.IEnumerator en = ((VTreeNode)tree.vTreeView.Items[0]).preorderEnumeration();

                //while (en.MoveNext())
                //{
                //    VTreeNode node = (VTreeNode)en.Current;

                //   if(node.Node_ID.Equals(id))
                //   {

                //       myTreeNode = node;
                //       break;
                //    }
                //}

                myTreeNode = tree.vTreeView.FindName(id.ToString());


                // myTreeNodeArray =  Get   tree.vTreeView.Items.IndexOf(  vTreePanel.vTreeView.Nodes.Find(id.ToString(), true);

                // if (myTreeNodeArray.GetLength(0) != 0)
                //{
                //select node in treeview
                if (myTreeNode != null)
                {


                    DependencyObject node = ((TreeViewItem)myTreeNode).Parent;
                    while (node != null)
                    {
                        ((TreeViewItem)node).IsExpanded = true;

                        if (((TreeViewItem)node).Parent is TreeViewItem)
                        {
                            node = ((TreeViewItem)node).Parent;
                        }
                        else node = null;
                    }
                    //tree.vTreeView.SelectItem(myTreeNode);


                    Dispatcher.BeginInvoke(delegate
                    {
                        isPostionSetting = true;
                        ((TreeViewItem)myTreeNode).IsSelected = true;
                        myTreeNode = null;
                        isPostionSetting = false;

                    });
                    //if (tree.vTreeView.GetScrollHost() != null)
                    //{
                    //    tree.vTreeView.GetScrollHost().ScrollIntoView((FrameworkElement)myTreeNode);
                    //}
                    //tree.vTreeView.ExpandSelectedPath();
                    //((TreeViewItem)myTreeNode).GetScrollHost().ScrollIntoView(
                }
                //myTreeNode = null;
                //vTreePanel.SetCurrentLevel();
                //}
                isPostionSetting = false;
                //}
            }
        }


        /// <summary>
        ///Row Changed - synchronize with Tree
        /// </summary>
        /// <param name="save"></param>
        /// <param name="keyID">true the row was saved (changed/added), false if the row was deleted</param>
        public void RowChanged(bool save, int keyID)
        {
            if (tree == null || keyID <= 0)
                return;
            String name = mTab.GetValue("Name").ToString();
            String description = (string)mTab.GetValue("Description");
            bool? isSummary = (bool?)mTab.GetValue("IsSummary");
            bool summary = isSummary != null && isSummary.Value;
            String imageIndicator = (string)mTab.GetValue("Action");  //  Menu - Action

            tree.NodeChanged(save, keyID, name, description, summary, imageIndicator);
        }   //  r


        /// <summary>
        /// Remove Events Called from Dispose function
        /// </summary>
        private void RemoveEvents()
        {
            try
            {
                for (int i = 0; i < vPanel.ctrlForBindData.Count; i++)
                {
                    IControl vControl = vPanel.ctrlForBindData[i];
                    //((Control)vControl).DataBindings.Clear();
                    vControl.VetoableChangeListener -= new EventHandler(aPanel.ValueChanged);
                    if (vControl is ITextChangedEvent)
                    {
                        ((ITextChangedEvent)vControl).FireTextChanged -= new EventHandler(aPanel.FireTextChanged);
                    }
                    if (vControl.GetDisplayType() == DisplayType.Button)
                    {
                        ((Button)vControl).Click -= new RoutedEventHandler(aPanel.btn_click);
                    }
                }
                // vTable.CellEndEdit -= new DataGridViewCellEventHandler(vTable_CellEndEdit);
                //vTable.DataBindings.Clear();
                mTab.GetTableObj().VetoableChange -= new EventHandler(GridController_VetoableChange);
                mTab.GetTableObj().FireDataStatusEvent -= new DataStatusEEventHandler(GridController_FireDataStatusEvent);

                if (bindingSource != null)
                {
                    bindingSource.Sorting -= new EventHandler<CustomSortEventArgs>(bindingSource_Sorting);
                    bindingSource.Sorted -= new EventHandler<SortedEventArgs>(bindingSource_Sorted);
                }

                //if (vTreePanel != null)
                //{
                //    vTreePanel.vTreeView.AfterSelect -= new TreeViewEventHandler(vTreeView_AfterSelect);
                //}
            }
            catch
            {
            }
        }

        /// <summary>
        /// Position Changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPositionChanged()
        {
            if (aPanel != null && !isPostionSetting)
            {
                //aPanel.PositionChanging();  //Order matter
                mTab.CurrentRowDataObject = currentRow;
                mTab.CurrentRow = currentRowIndex;
                aPanel.SetToolStripButtons();
                //aPanel.SetNavigateButtons();
                SetSelectedTreeNode();


                if (_datastatusEvent != null)
                {
                    _datastatusEvent.SetInfo("NavigateOrUpdate", null, false, false);
                }

                if (!LoadDependentInfo())
                {
                    DynamicDisplay("");
                    FireDataStatusEvent();
                }
            }
            else if (aPanel == null)
            {
                if (currentRow != null)
                {
                    mTab.CurrentRowDataObject = currentRow;
                    mTab.CurrentRow = currentRowIndex;
                }

            }
            //if(!isNavigationButton)
            //{
            //    aPanel.BindingSource_PositionChanged(sender, e);
            //    mTab.CurrentRowData = this.BindingSource.Current as DataRowView;
            //    mTab.CurrentRow = this.BindingSource.Position;
            //}
        }


        private bool LoadDependentInfo()
        {
            /**
             * Load Order Type from C_DocTypeTarget_ID
             */
            if (mTab.GetTableName().Equals("C_Order"))
            {

                int C_DocTyp_ID = 0;
                //int target = (Integer)GetValue("C_DocTypeTarget_ID");

                Object oo = mTab.GetValue("C_DocTypeTarget_ID");
                if (oo == null || oo == DBNull.Value)
                    return false;
                int.TryParse(oo.ToString(), out C_DocTyp_ID);
                if (C_DocTyp_ID == 0)
                    return false;

                ThreadPool.QueueUserWorkItem(delegate
                {
                    String sql = "SELECT DocSubTypeSO FROM C_DocType WHERE C_DocType_ID=" + C_DocTyp_ID;
                    try
                    {
                        object orderType = DataBase.DB.ExecuteScalar(sql);
                        // string orderType = DataBase.DB.ExecuteScalar(sql).ToString();
                        Envs.GetCtx().SetContext(mTab.GetWindowNo(), "OrderType", orderType == null ? "0" : orderType.ToString());
                    }
                    catch (Exception e)
                    {
                        log.Log(Level.SEVERE, "LoadDependentInfo", e);
                    }
                    Dispatcher.BeginInvoke(delegate
                    {
                        DynamicDisplay("");
                        FireDataStatusEvent();
                    }
                    );
                });
                System.Threading.Thread.Sleep(5);
                return true;
            }   //  loadOrderInfo
            return false;
        }   //  loadDependentInfo




        /// <summary>
        /// Show Staus label mess 
        /// </summary>
        private void FireDataStatusEvent()
        {
            try
            {
                if (_datastatusEvent == null)
                {
                    _datastatusEvent = new DataStatusEvent(this, this.bindingSource.Count,
                       false, Utility.Envs.GetContext().IsAutoCommit(windowNo), false);
                    _datastatusEvent.SetPageInfo(mTab.GetTableObj().GetCurrentPage(), mTab.GetTotalRowCount(), mTab.GetTableObj()._pazeSize);
                }
                _datastatusEvent.SetTotalRows(this.bindingSource.Count);
                if (_datastatusEvent.GetCurrentRow() != currentRowIndex)
                {
                    _datastatusEvent.SetCurrentRow(currentRowIndex);

                    if (_datastatusEvent.GetCurrentRow() >= 0)
                    {
                        _datastatusEvent.Created = (DateTime?)mTab.GetValue("Created");
                        _datastatusEvent.CreatedBy = Convert.ToInt32(mTab.GetValue("CreatedBy"));
                        _datastatusEvent.Updated = (DateTime?)mTab.GetValue("Updated");
                        _datastatusEvent.UpdatedBy = Convert.ToInt32(mTab.GetValue("UpdatedBy"));
                        _datastatusEvent.Record_ID = mTab.GetRecord_ID();
                        _datastatusEvent.AD_Table_ID = mTab.GetAD_Table_ID();
                        //  Info
                        StringBuilder info = new StringBuilder(mTab.GetTableName());
                        //  We have a key column
                        if (mTab.GetKeyColumnName() != null && mTab.GetKeyColumnName().Length > 0)
                        {
                            info.Append(" - ")
                                .Append(mTab.GetKeyColumnName()).Append("=").Append(_datastatusEvent.Record_ID);
                        }
                        else    //  we have multiple parents
                        {
                            for (int i = 0; i < mTab.GetParentColumnNames().Count; i++)
                            {
                                String keyCol = mTab.GetParentColumnNames()[i];
                                info.Append(" - ")
                                    .Append(keyCol).Append("=").Append(mTab.GetValue(keyCol));
                            }
                        }
                        _datastatusEvent.Info = info.ToString();
                    }
                    _datastatusEvent.SetInserting(mTab.GetTableObj().IsInserting());
                }

                String status = _datastatusEvent.GetAD_Message();
                if (status == null || status.Length == 0)
                    _datastatusEvent.SetInfo("NavigateOrUpdate", null, false, false);
                if (Dispatcher.CheckAccess())
                {
                    aPanel.SetStatusLine(_datastatusEvent);
                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        aPanel.SetStatusLine(_datastatusEvent);
                    });
                }
            }
            catch
            {

            }
        }

        ///// <summary>
        ///// Open RecordPopUp
        ///// </summary>
        //public void OpenRecordWin(string text)
        //{

        //    if (_datastatusEvent == null
        //    || _datastatusEvent.CreatedBy == null
        //    || !MRole.GetDefault().IsShowPreference())
        //        return;
        //    //
        //    String title = Utility.Msg.GetMsg(Utility.Envs.GetContext(), "Who") + text;
        //    // RecordInfo info = new RecordInfo(Env.getFrame(this), title, m_dse);
        //    // AEnv.showCenterScreen(info);
        //    ShowMessage.Info("Record_Id is  ", false, _datastatusEvent.Record_ID.ToString(), "");

        //}


        /// <summary>
        ///Get Model Tab
        /// </summary>
        /// <returns></returns>
        public GridTab GetMTab()
        {
            return mTab;
        }   //

        /// <summary>
        ///Is Tab displayed
        /// </summary>
        /// <returns>true if displayed</returns>
        public bool IsDisplayed()
        {
            return mTab.IsDisplayed(false);
        }	//	IsDisplayed

        /// <summary>
        /// Get tab level
        /// </summary>
        /// <returns></returns>
        public int GetTabLevel()
        {
            return mTab.GetTabLevel();
        }

        /// <summary>
        ///	Get Title
        /// </summary>
        /// <returns></returns>
        public String GetTitle()
        {
            return mTab.GetName();
        }	//	getTitle

        /// <summary>
        ///Set Window level Mnemonics
        /// </summary>
        /// <param name="set">true if set otherwise unregiser</param>
        public void SetMnemonics(bool set)
        {
            //if (vPanel != null)
            //    vPanel.SetMnemonics(set);
        }	//	setMnemonics

        /// <summary>
        /// Request focus in window
        /// </summary>
        /// 
        private bool isFirstTime = true;
        public bool RequestFocusInWindow()
        {
            if (singleRow && vPanel != null)
            {
                if (vPanel.RequestFocusInWindow())
                {
                    return true;
                }
                return vPanelViewer.Focus();
            }
            //this.Focus();

            if (!singleRow && vTable != null && vTable.SelectedItem != null && vTable.Columns.Count > 0)
            {
                try
                {
                    //vTable.ScrollIntoView(
                    if (!isFirstTime) //Error in Select First DataRow peer
                        vTable.ScrollIntoView(vTable.SelectedItem, vTable.Columns[0]);
                    else
                        isFirstTime = false;
                }
                catch
                {
                }
                return vTable.Focus();
            }
            return true;
        }

        public int RowCount()
        {
            return this.bindingSource.Count;
        }

        //public Size GetTableSize()
        //{
        //    return vPanel.GetTable().Size;
        //}
        //bool _settingValue;
        //public void SettingValue(bool val)
        //{
        //    _settingValue = VAddressColumn;
        //}

        //private void VetoableChangeListener(object sender, EventArgs e)
        //{
        //    if (!singleRow || _settingValue)
        //    {
        //        return;
        //    }
        //    SetButton();
        //}


        //private void FireTextChanged(object sender, EventArgs e)
        //{
        //    SetButtons();
        //}

        //private void SetButton()
        //{
        //    if (vTable != null)
        //    {
        //        vTable.NotifyCurrentCellDirty(true);
        //    }
        //}
        public IList GetSelectedRows()
        {
            return vTable.SelectedItems;
        }

        public List<DataGridRow> GetSelectedDataGridRow()
        {
            IList rowSource = vTable.SelectedItems;
            List<DataGridRow> rows = new List<DataGridRow>();
            for (int i = 0; i < rowSource.Count; i++)
            {
                DataUtil.DataObject obj = (DataUtil.DataObject)rowSource[i];


                FrameworkElement el = vTable.Columns.Last().GetCellContent(obj);

                if (el == null)
                {
                    //rows = null;
                }
                else
                {
                    DataGridRow row1 = DataGridRow.GetRowContainingElement(el.Parent as FrameworkElement);
                    if (row1 != null)
                        rows.Add(row1);
                }

            }

            return rows;
        }

        public Dictionary<String, string> GetColumnsName()
        {
            //var r = (from t in vTable.Columns
            //         select t);
#if DEBUG
            for (int i = 0; i < vTable.Columns.Count; i++)
            {
                System.Diagnostics.Debug.WriteLine(vTable.Columns[i].Header.ToString());
            }
#endif
            var d = vTable.Columns.ToDictionary(o => ((IDataGridColumn)o).DataPropertyName, o => o.Header.ToString());
            return d as Dictionary<string, string>;
        }


        //public void SetTabName(string name)
        //{
        //    lblTabName.Text = name;
        //}

        //internal void DoPaint()
        //{
        //    if (vTable != null)
        //    {
        //        vTable.PaintGrid();
        //    }
        //}

        public void Dispose()
        {
            RemoveEvents();
            mTab = null;
            aPanel = null;
            _datastatusEvent = null;
            vPanel.Dispose();
            vPanel = null;
            vTable.ItemsSource = null;
            if (bindingSource != null)
            {
                bindingSource.Clear();
                bindingSource = null;
            }
            if (rightPaneLinkItems != null)
            {
                rightPaneLinkItems.Clear();
                rightPaneLinkItems = null;
            }
            if (leftPaneLinkItems != null)
            {
                leftPaneLinkItems.Clear();
                leftPaneLinkItems = null;
            }
        }

        internal IList GetDataSource()
        {
            return null;// bindingSource;
        }

        internal BindingSource GetBindingSource()
        {
            return bindingSource;
        }

        #region IBusy



        IBusy _iBusy = null;

        internal void RegisterIBusy(IBusy iBusy)
        {
            _iBusy = iBusy;
        }
        internal void UnRegisterAccount()
        {
            _iBusy = null;
        }


        public VDataGrid GetVDataGrid()
        {
            return vTable;
        }

        #endregion


        public Dictionary<string, string> GetFieldVlaues()
        {
            Dictionary<string, string> fieldValues = new Dictionary<string, string>();
            //  for (int i = 0; i < vPanel.ctrlForBindData.Count; i++)
            for (int i = 0; i < vPanel.allControls.Count; i++)
            {
                //IControl comp = vPanel.ctrlForBindData[i];
                ////IControl compI = (IControl)comp;
                //String columnName = comp.GetName();
                IControl comp = vPanel.allControls[i];
                //IControl compI = (IControl)comp;
                String columnName = comp.GetName();

                if (columnName.StartsWith("lbl"))
                {
                    columnName = columnName.Substring(3);
                    continue;
                }
                GridField mField = mTab.GetField(columnName);

                string text = comp.GetText();
                fieldValues[columnName] = text;

            }
            return fieldValues;

        }

        /**
   *  Get Key ID of row
   *  @param  row row number
   *  @return The Key ID of the row or -1 if not found
   */
        public int GetKeyID(int row, String colName)
        {
            if (bindingSource != null && bindingSource.Count > 0 && bindingSource.Count > row)
            {
                object rowData = bindingSource[row];

                object id = ((DataUtil.DataObject)rowData).GetFieldValue(colName.ToUpper());
                //return m_mTable.getKeyID(row);

                try
                {
                    return Convert.ToInt32(id);
                }
                catch
                {
                    return -1;
                }

            }
            return -1;
        }

        /// <summary>
        /// refresh Row number sequence
        /// </summary>
        internal void RefreshGrid()
        {
            vTable.PaintRow();
        }
    }

    public class DeleteEventArgs : EventArgs
    {
        public bool IsDeleted
        {
            get;
            set;
        }
        public DeleteEventArgs(bool isDeleted)
        {
            IsDeleted = isDeleted;
        }
    }

    public class NewEventArgs : EventArgs
    {
        public bool IsNew
        {
            get;
            set;
        }
        public NewEventArgs(bool isNew)
        {
            IsNew = isNew;
        }
    }
}
